/**
 * 
 */
package com.xb.cloud.product.merchant.service.impl;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.xb.cloud.common.client.bo.PageBo;
import com.xb.cloud.common.constant.DbConstants;
import com.xb.cloud.common.model.PageParam;
import com.xb.cloud.common.util.KeyUtils;
import com.xb.cloud.product.merchant.inner.service.ProductDescriptionInnerService;
import com.xb.cloud.product.merchant.inner.service.ProductPicInnerService;
import com.xb.cloud.product.merchant.inner.service.ProductSkuExtDescInnerService;
import com.xb.cloud.product.merchant.inner.service.ProductSkuExtPicInnerService;
import com.xb.cloud.product.merchant.inner.service.ProductSkuInnerService;
import com.xb.cloud.product.merchant.inner.service.ProductSkuPriceInnerService;
import com.xb.cloud.product.merchant.inner.service.ShopNavigationGroupInnerService;
import com.xb.cloud.product.merchant.service.client.ProductMongoService;
import com.xb.cloud.product.merchant.service.client.ProductPublishService;
import com.xb.cloud.product.merchant.service.client.bo.EndMerchantUserBo;
import com.xb.cloud.product.merchant.service.client.bo.ProductPicBo;
import com.xb.cloud.product.merchant.service.client.bo.ProductShopSeriesMongoBo;
import com.xb.cloud.product.merchant.service.client.bo.ProductSummaryBo;
import com.xb.cloud.product.merchant.service.client.bo.ProductTemplateBo;
import com.xb.cloud.product.merchant.service.client.input.bo.ProductSkuInputBo;
import com.xb.cloud.product.merchant.service.client.input.bo.ProductSkuPicInputBo;
import com.xb.cloud.product.service.business.model.Product;
import com.xb.cloud.product.service.business.model.ProductExample;
import com.xb.cloud.product.service.business.model.ProductExamplePaged;
import com.xb.cloud.product.service.business.model.mapper.ProductMapper;
import com.xb.cloud.service.client.ServiceReturnInfo;
import com.xb.cloud.service.client.ServiceReturnUtils;

/**
 * 
 * 产品发布服务类;
 * 
 * @author kexue
 *
 */
@Service("productPublishService")
public class ProductPublishServiceImpl extends AbstractService implements ProductPublishService {

	private static final Logger LOGGER = LoggerFactory.getLogger(ProductPublishServiceImpl.class);

	@Resource
	private ProductMapper productMapper;

	@Resource
	private ProductPicInnerService productPicInnerService;
	
	@Resource
	private ProductDescriptionInnerService  productDescriptionInnerService;

	// -------服务依赖---------------

	@Resource
	private ProductSkuInnerService  productSkuInnerService;

	@Resource
	private ProductSkuExtPicInnerService productSkuExtPicInnerService;

	@Resource
	private ProductSkuPriceInnerService productSkuPriceInnerService;

	@Resource
	private ProductSkuExtDescInnerService productSkuExtDescInnerService;

	@Resource
	private ProductMongoService productMongoService;
	

	@Resource
	private ShopNavigationGroupInnerService  shopNavigationGroupInnerService;

	/**
	 * 根据类目id获取该类目节ShopNavigationGroupServiceImpl点下的可发布的商品列表; [分页] --该类目下当前商家、店铺未发布的商品
	 * 
	 * @param categoryId
	 *            : 类目id
	 * @param shopId
	 *            : 店铺id
	 * @param pageNum
	 *            : 分页编号
	 * @param pageSize
	 *            : 分页数据列表大小
	 */
	@Override
	public ServiceReturnInfo getPublishableProductSummaryBoListByCategoryId(Long categoryId, Long companyId,
			Long shopId, Integer pageNum, Integer pageSize) {

		PageBo<ProductSummaryBo> productSummaryBoListPage = new PageBo<ProductSummaryBo>();

		ProductExamplePaged productExample = new ProductExamplePaged();

		productExample.setCategoryId(categoryId);
		productExample.setIsDeleted(DbConstants.IS_DELETED_FALSE);
		productExample.setIsEnabled(DbConstants.TRUE);

		productExample.setCompanyId(companyId);
		productExample.setCompanyLevel(true);
		productExample.setShopId(shopId);
		//未发布排在前面
		productExample.setOrderBySkuIdAsc("true");

		// 单品 、系列品虚品
		productExample.setProductTypeList(
				Arrays.asList(DbConstants.PRODUCT_TYPE_SINGLE, DbConstants.PRODUCT_TYPE_SERIAS_VIRTUAL));
		int count = (int) productMapper.countPublishableProductSummaryBoByExample(productExample);
		if (count > 0) {
			PageParam pageParam = new PageParam(pageNum, pageSize);
			productExample.setPageParam(pageParam);
			List<ProductSummaryBo> productSummaryBoList = productMapper
					.selectPublishableProductSummaryBoListByExample(productExample);
			for (ProductSummaryBo summaryBo : productSummaryBoList) {
//				if (summaryBo.getProductType().byteValue() == DbConstants.PRODUCT_TYPE_SINGLE) {
					ProductPicBo productPicBo = productPicInnerService.getDefaultPicListByProductId(summaryBo.getId());
					if(productPicBo!=null){
						summaryBo.setDefaultPicUrl(productPicBo.getPicUrl());
					}
//				} else {
//					// 虚品id
//					ProductPicBo productPicBo = productPicInnerService
//							.getDefaultPicByrVirtualProductId(summaryBo.getId());
//					if(productPicBo!=null){
//						summaryBo.setDefaultPicUrl(productPicBo.getPicUrl());
//					}
//				} 
			}
			productSummaryBoListPage.setRows(productSummaryBoList);
			productSummaryBoListPage.setTotal(count);
		}
		return ServiceReturnUtils.success(productSummaryBoListPage);
	}

	
	/** 
	 *  merchant级别的product.
	 */
	@Override
	public ServiceReturnInfo getPublishableProductSummaryBoListMerchantLevelByCategoryId(Long categoryId, Long merchantId,
			Long shopId, Integer pageNum, Integer pageSize) {

		PageBo<ProductSummaryBo> productSummaryBoListPage = new PageBo<ProductSummaryBo>();

		ProductExamplePaged productExample = new ProductExamplePaged();

		productExample.setCategoryId(categoryId);
		productExample.setIsDeleted(DbConstants.IS_DELETED_FALSE);
		productExample.setIsEnabled(DbConstants.TRUE);

		productExample.setMerchantId(merchantId);
		productExample.setCompanyLevel(false);
		productExample.setShopId(shopId);
		//未发布排在前面
		productExample.setOrderBySkuIdAsc("true");

		// 单品 、系列品虚品
		productExample.setProductTypeList(
				Arrays.asList(DbConstants.PRODUCT_TYPE_SINGLE, DbConstants.PRODUCT_TYPE_SERIAS_VIRTUAL));
		int count = (int) productMapper.countPublishableProductSummaryBoByExample(productExample);
		if (count > 0) {
			PageParam pageParam = new PageParam(pageNum, pageSize);
			productExample.setPageParam(pageParam);
			List<ProductSummaryBo> productSummaryBoList = productMapper
					.selectPublishableProductSummaryBoListByExample(productExample);
			for (ProductSummaryBo summaryBo : productSummaryBoList) {
//				if (summaryBo.getProductType().byteValue() == DbConstants.PRODUCT_TYPE_SINGLE) {
					ProductPicBo productPicBo = productPicInnerService.getDefaultPicListByProductId(summaryBo.getId());
					if(productPicBo!=null){
						summaryBo.setDefaultPicUrl(productPicBo.getPicUrl());
					}
//				} else {
//					// 虚品id
//					ProductPicBo productPicBo = productPicInnerService
//							.getDefaultPicByrVirtualProductId(summaryBo.getId());
//					if(productPicBo!=null){
//						summaryBo.setDefaultPicUrl(productPicBo.getPicUrl());
//					}
//				} 
			}
			productSummaryBoListPage.setRows(productSummaryBoList);
			productSummaryBoListPage.setTotal(count);
		}
		return ServiceReturnUtils.success(productSummaryBoListPage);
	}



	/**
	 * 根据productId 获取product模板.
	 * 
	 * @return
	 */
	@Override
	public ServiceReturnInfo getProductTemplateBoByProductId(Long productId) {

		ProductExample productExample = new ProductExample();
		com.xb.cloud.product.service.business.model.ProductExample.Criteria createCriteria = productExample
				.createCriteria();
		createCriteria.andIsDeletedEqualTo(DbConstants.FALSE);
		createCriteria.andIsEnabledEqualTo(DbConstants.TRUE);
		createCriteria.andIdEqualTo(productId);

		List<Product> productList = productMapper.selectByExample(productExample);
		if (productList != null && productList.size() > 0) {
			ProductTemplateBo productTemplateBo = new ProductTemplateBo();
			BeanUtils.copyProperties(productList.get(0), productTemplateBo);
			//图片设置
			productTemplateBo.setProductPicBoList(productPicInnerService.getPicListByProductId(productId));
			//文本描述
			productTemplateBo.setProductDetailContent(productDescriptionInnerService.getDescriptionById(productId)); 
			return ServiceReturnUtils.success(productTemplateBo);
		}

		return ServiceReturnUtils.success();
	}

	/**
	 * 发布Sku (product库相关表的更新/插入在一个事务里面)
	 * 
	 * @param productId1
	 *            ： 单品id / 系列品的虚品id
	 * @param productId2
	 *            ： productType=0时候当前字段为空 / 系列品的系列产品对应的子品Id
	 * @param shopId:
	 *            店铺 Id
	 * @param productType
	 *            : productId1对应的产品类型 ， 0:主品 ; 1:虚品
	 * @param detailContent
	 *            : 图文详情的html
	 * @param skuNameCn
	 * @param skuTitleSub
	 * @param price
	 *            : 价格
	 * @param stock:库存
	 * @param groupIdList : 店铺内分组id列表
	 */

	@Transactional(propagation = Propagation.REQUIRED,value="transactionManager_product")
	@Override
	public ServiceReturnInfo createProductSku(EndMerchantUserBo endMerchantUserBo, Long productId1, Long productId2,
			Byte productType, List<ProductSkuPicInputBo> skuPics, String detailContentJson,
			ProductSkuInputBo skuInput, BigDecimal priceMarket, BigDecimal priceSale,List<Long> groupIdList) {
		Long actualProductId = null;

		// 1.保存sku
		Long productSkuId = productSkuInnerService.createSku(skuInput, endMerchantUserBo);
		 
		 
		if (DbConstants.PRODUCT_TYPE_SERIAS_VIRTUAL == productType.byteValue()){
			// 系列品
			actualProductId = productId2;
		} else {
			// 单品
			actualProductId = productId1;
		}

		 // 2.保存图片
		 productSkuExtPicInnerService.createSkuExtPics(skuPics, productSkuId,
				endMerchantUserBo);
		 

		// 3.保存价格
		 productSkuPriceInnerService.createSkuPrice(priceMarket, priceSale,
				actualProductId, productSkuId, endMerchantUserBo);
		 

		// 4.保存文本描述
		 productSkuExtDescInnerService.createSkuExtDesc(detailContentJson, productSkuId,
				endMerchantUserBo);
		 
		// 5. 保存系列品组合 mongo 增加seriesAttributeComb -> skuId的映射
		if(DbConstants.PRODUCT_TYPE_SERIAS_VIRTUAL==productType.byteValue()){
			String generateProductShopKey = KeyUtils.generateProductShopKey(productId1, endMerchantUserBo.getShopId());
			ServiceReturnInfo pMongoReturnInfo = productMongoService
					.findByProductShopId(generateProductShopKey);
			ProductShopSeriesMongoBo seriesMongo = (ProductShopSeriesMongoBo) pMongoReturnInfo.getData(); 
			if(seriesMongo==null){
				seriesMongo=new ProductShopSeriesMongoBo();
				seriesMongo.setProductIdshopId(generateProductShopKey);
			}else{
				if (KeyUtils.checkExistSeriesComb(skuInput.getSeriesAttributeComb(),
						seriesMongo.getSeriesAttributeCombSkuIdMap())) {
					throw new RuntimeException("product系列组合sku mongo数据已存在");
				}
			}
			Map<String, Long> seriesAttributeCombSkuIdMap = seriesMongo.getSeriesAttributeCombSkuIdMap();
			seriesAttributeCombSkuIdMap.put(skuInput.getSeriesAttributeComb(), productSkuId);
			
			ServiceReturnInfo returnInfo = productMongoService.saveProductShopSeriesMongoBo(seriesMongo);
			if (ServiceReturnUtils.isError(returnInfo)) {
				throw new RuntimeException("product系列组合 mongo数据失败");
			}
		}
		
		//6.插入sku分组关联 
		if(groupIdList!=null&& groupIdList.size()>0){
			 shopNavigationGroupInnerService.createShopNavicationGroupSkuRef(productSkuId, groupIdList, endMerchantUserBo);
		 }
		 
		return ServiceReturnUtils.success(productSkuId);
	}

}
